3.6 Виджеты. Text Image Icon
8 из 8 шагов пройдено

Виджеты. Text Image Icon

➡️Скачать презентацию. Flutter Text Image Icon
➡️Скачать шпаргалку
➡️Ссылка на репозиторий с кодом этого урока

Виджеты для работы с текстом

Виджет Text

Самый популярный виджет это Text()
Он имеет 2 разновидности:

  • Text() - Стандартный текст
  • RichText() - Возможность форматировать части текста
  • В папке widgets добавим файл text_widget.dart
  • Напишем виджет TextExample
  • Добавим Text и рассмотрим все способы стилизации

Файл text_widget.dart

class TextExample extends StatelessWidget {
  const TextExample({super.key});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(
        "Вкусные Роллы",
        style: TextStyle(),
      ),
    );
  }
}

В файле main.dart , внутри виджета MyApp() в параметр body передаём виджет TextExample чтобы его стало видно на экране.

Файл main.dart

import 'package:flutter/material.dart';
import 'widgets/text_widget.dart'; // 🡰 Импортируем для работы с TextExample

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: "Flutter Course",
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
      ),
      // 👉 Возвращаем временно Scaffold
      home: Scaffold(
        appBar: AppBar(
          centerTitle: true, 
          title: const Text("Виджет Text"),
        ),
        body: TextExample(), // 🡰 Сюда
      ),
    );
  }
}

TextStyle() позволяет добавлять стили для текста

Файл text_widget.dart

import 'package:flutter/material.dart';

class TextExample extends StatelessWidget {
  const TextExample({super.key});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(
        "Вкусные Роллы",

        style: TextStyle(
          fontSize: 32.0, // Размер текста
          color: Colors.blue, // Цвет текста
          fontStyle: FontStyle.italic, // Начертание
          fontWeight: FontWeight.w700, // Жирность текста
          decoration: TextDecoration.underline, // Подчеркивание
          decorationStyle: TextDecorationStyle.solid, // Линия
          decorationColor: Colors.red, //* Цвет для линии
          letterSpacing: 2.5, //* Расстояние между буквами
        ),
      ),
    );
  }
}

Файл text_widget.dart

import 'package:flutter/material.dart';

class TextExample extends StatelessWidget {
  const TextExample({super.key});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(
        "Вкусные Роллы",
        style: TextStyle(
          fontSize: 32.0, // Размер текста
          color: Colors.blue, // Цвет текста
          fontStyle: FontStyle.normal, // Начертание
          fontWeight: FontWeight.w700, // Жирность текста
          decoration: TextDecoration.underline, // Подчеркивание
          decorationStyle: TextDecorationStyle.dashed, // Линия
          decorationColor: Colors.black, // Цвет для линии
          letterSpacing: 0, // Расстояние между буквами
        ),
      ),
    );
  }
}

Расcмотрим ещё некоторые свойства виджета Text() 

import 'package:flutter/material.dart';

class TextExample extends StatelessWidget {
  const TextExample({super.key});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        color: Colors.blue,
        height: 170,
        child: Text(
        "Вкусные Роллы",
        style: TextStyle(
          fontSize: 72.0,
          color: Colors.white,
          fontStyle: FontStyle.italic,
          fontWeight: FontWeight.w700,
          decoration: TextDecoration.underline,
          decorationStyle: TextDecorationStyle.solid,
          decorationColor: Colors.red,
          wordSpacing: 2.5,
        ),

        // Расположение текста внутри блока
        textAlign: TextAlign.center, // по центру

        // Если текст не вмещается в контейнер, то перенеси строки
        softWrap: true,

        // Если не поможет softWrap, то использовать overflow
        // overflow: TextOverflow.clip,       // Обрезать текст
        // overflow: TextOverflow.ellipsis,  // Использовать многоточие
        // overflow: TextOverflow.visible,   // Показать, переполнение
        overflow: TextOverflow.fade,      // Сделать невидимым

        maxLines: 2, // Кол-во видимых линий, при переносе текста
        textDirection: TextDirection.ltr, // Направление текста
            ),
      ),

    );
  }
}


Будьте вежливы и соблюдайте наши принципы сообщества. Пожалуйста, не оставляйте решения и подсказки в комментариях, для этого есть отдельный форум.
Оставить комментарий